<template>
    <Header title="购物车"/>
    <div class="cartDetails">
        <div v-for="c in cart_list" class="cart_detail">
            <CartItem :item = "c"></CartItem>
        </div>
        
    </div> 
    <div class="result">
        <input type="checkbox" class="toggleAll" v-model="toggleAll" />
        <div class="total">总价：￥ {{ totalPrice }}</div>
        <button @click="createOrder">生成订单</button>

    </div>
    <Footer></Footer>
</template>


<script setup>
import Header from '@/components/Header.vue';
import Footer from '@/components/Footer.vue';
import CartItem from './CartItem.vue';
import { computed, reactive, toRefs } from 'vue';
import {useOrderStore} from '@/store/OrderStore'
import { useRouter } from 'vue-router';

    const orderStore = useOrderStore()
    const router = useRouter()

    const data = reactive({
        cart_list:[
            {title:'小炒肉',pic:'https://img1.baidu.com/it/u=3392421079,3027698000&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=644',count:1,price:12,checked:false},
            {title:'酸菜鱼',pic:'https://img1.baidu.com/it/u=3392421079,3027698000&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=644',count:1,price:10,checked:true},
            {title:'麻辣鱼',pic:'https://img1.baidu.com/it/u=3392421079,3027698000&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=644',count:1,price:12,checked:false}
        ]
    })

    const {cart_list} = {...toRefs(data)}


    //总金额
    const totalPrice = computed(()=>{
        return cart_list.value.filter(item=>item.checked).reduce((sum,item)=>{
            return sum + item.price * item.count
        },0)
    })

    //总数量
    const totalQuantity = computed(()=>{
        return cart_list.value.filter(item=>item.checked).reduce((sum,item)=>{
            return sum + item.count
        },0)
    })

    

    const count = computed(()=>data.cart_list.filter(item=>!item.checked).length)
    

    const toggleAll = computed({
        get(){
            return count.value == 0
        },
        set(state){
            data.cart_list.forEach(item=>item.checked = state)
        }

    })




    //生成订单
    function createOrder(){
        //生成订单编号
        const order = {orderId:Date.now(),price:totalPrice,count:totalQuantity}
        orderStore.addOrder(order)

        //跳转到订单页面显示所有订单
        router.push('/order')
    }



    
</script>


<style lang="less">
  .cartDetails{
    margin-top:10px;
  }

  .result{
    display: flex;
    padding:10px;
    justify-content: space-around;
    font-size: 10px;

    .toggleAll{
        width:10px;
        height: 10px;
    }

  }
</style>